import { useStore } from 'vuex';
import store from './store';

import wallet from './chain/wallet'
import { RouteLocationNormalizedGeneric, RouteLocationNormalizedLoadedGeneric, NavigationGuardNext } from "vue-router";

var gasPrice = 0;

// 当前网络错误为true
var install = localStorage.getItem("install") || "true"; // 钱包是否已经安装，存储为字符串
var accountsShow = localStorage.getItem("accountsShow") || "true";
var isLogin = localStorage.getItem("ISLOGININ"); // 登录状态，是否已经登录

export const getWebData = async (to: RouteLocationNormalizedGeneric, from: RouteLocationNormalizedLoadedGeneric, next: NavigationGuardNext) => {
  // 如果没有安装钱包，直接返回
  let walletName = localStorage.getItem('wallet');
  if(walletName == null){
    install = "true";
    localStorage.setItem("install", install);
    localStorage.removeItem("accounts");
    localStorage.removeItem("gasPrice");
    next();
    return;
  }

  install = "false";
 
  // 如果不是登录状态，直接跳转
  if (isLogin == "false") {
    store.dispatch("AccountsVal", "");
    localStorage.setItem("accounts", "");
    localStorage.setItem("accountsShow", 'false');
    // store.state.connectWallet = false;
    return next();
  }

  wallet.setCurrentWallet(walletName);
  await wallet.connect();
  console.log('=================',wallet.connected);
  console.log('=================',wallet.publicKey);
  if (wallet.connected) {
    const solanaPubKey = (wallet.publicKey as any).toBase58();
    console.log(solanaPubKey);
    accountsShow = "false";
    store.dispatch('chain/AccountsVal', solanaPubKey);
    localStorage.setItem("accounts", solanaPubKey);
    store.dispatch('chain/GasPriceVal', gasPrice);
    localStorage.setItem("gasPrice", String(gasPrice));  
  } else {
    accountsShow = "true";
    store.dispatch('chain/AccountsVal', "");
    localStorage.setItem("accounts", "");
  }

  localStorage.setItem("install", install);
  localStorage.setItem("accountsShow", accountsShow);

  next();
};
